package com.situ.mallsdauweb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.situ.mallsdauweb.config.AlipayConfigBean;
import com.situ.mallsdauweb.entity.OrderInfo;
import com.situ.mallsdauweb.mapper.OrderInfoMapper;
import com.situ.mallsdauweb.service.IPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @Date: 2023/6/6 20:12
 * @Author: 王辉
 * @Description:
 */
@Service
public class PayServiceImpl implements IPayService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private AlipayConfigBean alipayConfigBean;

//    @Value("${alipay.appId}")
//    private String appId;
//    @Value("${alipay.privateKey}")
//    private String privateKey;
//    @Value("${alipay.alipayPublicKey}")
//    private String alipayPublicKey;
//
//    @Value("${alipay.serverUrl}")
//    private String serverUrl;
//
//    @Value("${alipay.notifyUrl}")
//    private String notifyUrl;

    @Override
    public String pay(Integer id) throws AlipayApiException {

        OrderInfo oi = orderInfoMapper.selectById(id);
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfigBean.getServerUrl(),alipayConfigBean.getAppId(),alipayConfigBean.getPrivateKey(),"json","UTF-8",alipayConfigBean.getPublicKey(),"RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(alipayConfigBean.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", oi.getCode());
        bizContent.put("total_amount", oi.getPrice());
        bizContent.put("subject", "小果商品订单");

        request.setBizContent(bizContent.toString());
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return response.getQrCode();
        } else {
            return "";
        }
    }
}
